<template>
  <div class="UploadImageMutil">
    <template v-if="type == 'image'">
      <a-upload
        list-type="picture-card"
        :file-list="fileList"
        multiple
        @preview="handlePreview"
        :customRequest="uploadImage"
        @change="handleChange"
        :before-upload="beforeUpload"
        :accept="accept"
      >
        <div>
          <a-icon type="plus" />
        </div>
      </a-upload>
      <div class="ant-upload-text" v-html="des">

      </div>

      <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
        <img alt="" style="width: 100%" :src="previewImage" />
      </a-modal>
    </template>

    <template v-else-if="type=='button'">
      <a-upload
        name="file"
        :file-list="fileList"
        :multiple="true"
        :customRequest="uploadImage"
        @change="handleChange"
        :before-upload="beforeUpload"
        :accept="accept"
      >
        <a-button type="primary"> <a-icon type="upload" /> 点击上传 </a-button>
      </a-upload>
    </template>

    <template v-else-if="type=='input'">
      <a-upload
        name="file"
        :file-list="fileList"
        :multiple="true"
        :customRequest="uploadImage"
        @change="handleChange"
        :before-upload="beforeUpload"
        :accept="accept"
      >
        <div class="file" style="padding:0 10px;"><a-icon type="to-top" /> {{ text }}</div>

      </a-upload>
    </template>

    <template v-else>
      <a-upload-dragger
        :file-list="fileList"
        :multiple="true"
        :customRequest="uploadImage"
        @change="handleChange"
        :before-upload="beforeUpload"
        :accept="accept"
      >
        <p class="ant-upload-drag-icon">
          <a-icon type="inbox" />
        </p>
        <p class="ant-upload-text">
          点击或将文件拖拽到这里上传
        </p>
        <p class="ant-upload-hint">
          {{ text }}
        </p>
      </a-upload-dragger>
    </template>
  </div>
</template>

<script>
import { UploadImage } from '@/utils/uploadFiles';
import { isFile } from '@/utils/common';
import { preview } from '@/api/zcpd';

// import { showFile } from '@/api/common/index';

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

export default {
  name: 'UploadImageMutil',
  props: {
    accept: {
      type: String,
      default: '.pdf'
    },
    text: {
      type: String,
      default: '支持扩展名：pdf'
    },
    des: {
      type: String,
      default: ''
    },
    url: {
      type: Array,
      default: () => []
    },
    fileId: {
      type: String,
      default: ''
    },
    // 类型 默认全部， image -> 只传图片类型
    type: {
      type: String,
      default: ''
    },
    // 上传图片目录
    floder: {
      type: String,
      default: 'tempImage'
    },
    // 上传限制张数
    length: {
      type: Number,
      default: 20
    },
    data: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      previewVisible: false,
      imgurl: [],
      fileList: [],
      defaultFileList: [],
      previewImage: '',
      limit: 20
    };
  },
  computed: {
    isImage() {
      return this.type == 'image';
    }
  },
  watch: {
    url(n) {
      if (n.length) {
        const fileList = n.map(e => {
        return {
            url: preview(e.attachmentId),
            uid: e.attachmentId,
            name: e.attachmentName,
            status: 'done',
            response: '',
            attachmentIdList: e

          };
        });
        console.log(fileList);
        if (fileList instanceof Array) {
          this.fileList = fileList;
        }
      }
    }
  },
  components: {

  },
  created() {

  },
  mounted() {
    // if (this.fileId) {
    //   showFile({ ids: this.fileId }).then(res => {
    //     const fileList = res.data.map(e => {
    //     return {
    //         url: e.path,
    //         fileId: e.id,
    //         uid: e.id,
    //         name: e.fileName,
    //         status: 'done',
    //         response: ''
    //       };
    //     });
    //     if (fileList instanceof Array) {
    //       this.fileList = fileList;
    //     }
    //   });
    // } else if (this.url) {
    //   const fileList = this.url.map(e => {
    //     return {
    //         url: e.attachmentUrl,
    //         uid: String(new Date().getTime()),
    //         name: e,
    //         status: 'done',
    //         response: '',
    //         attachmentIdList: this.url.map(e => e.attachmentId)

    //       };
    //     });
    //     console.log(fileList);
    //     if (fileList instanceof Array) {
    //       this.fileList = fileList;
    //     }
    // } else {
    //   this.fileList = [];
    // }
  },

  methods: {
    handleCancel() {
      this.previewVisible = false;
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    handleChange(info) {
      const isAllow = isFile(info.file.name, this.type);
      if (!isAllow) {
        // this.$message.error('请上传正确的图片格式!');
        return false;
      }

      if (info.file.size > this.limit * 1024 * 1024) {
        return false;
      }

      // console.log(info.file.size, this.limit * 1024 * 1024);

      let fileList = [...info.fileList];
      if (fileList.length > this.length) {
        this.$message.error('最多上传' + this.length + '张');
        return;
      }

      fileList = fileList.map(file => {
        // console.log('file', file);
        if (file.response) {
          file.url = preview(file.response[0].attachmentId);
          file.attachmentIdList = file.response[0];
        }
        return file;
      });

      this.fileList = fileList;
      this.imgurl = fileList.filter(file => {
        return file.attachmentIdList;
      }).map(e => {
        return { url: e.url, attachmentIdList: e.attachmentIdList };
      });
      // const url = this.imgurl.map(e => {
      //   return e.url;
      // }).join(',');
      console.log('fileList', this.imgurl);
      this.$emit('getUrl', this.imgurl);
    },
    beforeUpload(file, fileList) {
      // console.log(this.type);
      const isAllow = isFile(file.name, this.type);
      if (!isAllow) {
        if (this.type == 1) {
          this.$message.error('仅支持上传.jpg,.jpeg,.png为后缀名的图片');
        } else if (this.type == 2) {
          this.$message.error('仅支持上传pdf');
        } else {
          this.$message.error('仅支持上传.bmp,.jpg,.jpeg,.png,.doc,.docx,.pdf,.xls,.xlsx为后缀名的文件!');
        }

        return false;
      }
      if (file.size > this.limit * 1024 * 1024) {
        this.$message.error('文件大小不能超过20兆!');
        return false;
      }
      return true;
    },
    uploadImage(e) {
      // console.log(e);
      UploadImage(e.file, this.type).then(res => {
        this.$emit('getRes', res);
        e.onSuccess(res);
      }).catch(err => {
        e.onFail(err);
      });
    }
  }
};
</script>

<style scoped>
  .UploadImageMutil .ant-upload-text {
    line-height: 1.2;
    margin-top: -12px;
  }
</style>
